package file.upload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//首先判断是否为多段数据，如果为多段数据才是文件上传

        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            FileItemFactory file = new DiskFileItemFactory();
            //创建用于解析上传文件的ServletFileUpload类
            ServletFileUpload load = new ServletFileUpload(file);
            try {
                //解析上传的数据，得到一个表单项FileTtem
                java.util.List<FileItem> list = load.parseRequest(req);
                //循环遍历每一个表单 并判断是普通类型还是上传的文件
                for (FileItem filee:list) {
                    //是普通类型
                    if(filee.isFormField()){
                        System.out.println("普通表单参数名："+filee.getFieldName());
                        System.out.println("普通表单参数值："+filee.getString("utf-8"));
                    } else {//上传的文件
                        System.out.println("上传文件表单参数名："+filee.getFieldName());
                        System.out.println("上传文件表参数值："+filee.getString());
                        filee.write(new File("E:\\Test\\"+filee.getName()));
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}
